/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.ui.statusbar

import android.car.Car
import android.car.VehicleAreaType
import android.car.hardware.CarPropertyValue
import android.car.hardware.property.CarPropertyManager
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.core.content.res.ResourcesCompat
import com.ecarx.systemui.plugin.R
import com.ecarx.systemui.plugin.ui.custom.SystemBarButton
import com.ecarx.systemui.plugin.utils.AppUtils
import com.ecarx.systemui.plugin.utils.LogUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import vendor.ecarx.xma.automotive.vehicle.V2_0.ECarXVehicleProperty

class AirPurgeView : SystemBarButton, CarPropertyManager.CarPropertyEventCallback {

    companion object {
        private const val TAG = "AirPurgeView"

        private const val PROP_HVAC_FUNC_IONS_SWITCH:Int = ECarXVehicleProperty.HVAC_FUNC_AUTO_ION

    }

    private var mCarPropertyManager: CarPropertyManager? = null


    constructor(context: Context?) : this(context!!, null) {}
    constructor(context: Context?, attrs: AttributeSet?) : this(context!!, attrs, 0) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!,
        attrs,
        defStyleAttr
    ) {

    }

    override fun getContentDescriptionString(): String {
        return "AirPurgeView"
    }

    override fun initView() {
        super.initView()

        setImageDrawable(
            ResourcesCompat
                .getDrawable(
                    resources,
                    R.drawable.ic_air_purge,
                    context.theme
                )
        )
        visibility = View.GONE

        setOnClickListener { v: View? ->
            AppUtils.startClimate(context, true)
        }

    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        registerVHALSignal()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        unregisterVHALSignal()
    }

    private fun registerVHALSignal() {
        CoroutineScope(Dispatchers.IO).launch {
            Car.createCar(context, null, 10000) { car, ready ->
                if (ready) {
                    LogUtils.d(TAG, "registerVHALSignal with CarService")
                    val carPropertyManager = car?.getCarManager(Car.PROPERTY_SERVICE) as CarPropertyManager

                    carPropertyManager.registerCallback(this@AirPurgeView, PROP_HVAC_FUNC_IONS_SWITCH, CarPropertyManager.SENSOR_RATE_NORMAL)

                    mCarPropertyManager = carPropertyManager
                    try {
                        val isOpen = mCarPropertyManager?.getBooleanProperty(
                            PROP_HVAC_FUNC_IONS_SWITCH,
                            VehicleAreaType.VEHICLE_AREA_TYPE_GLOBAL
                        )
                        showIcon(isOpen == true)
                    } catch (throwable: Throwable){
                        throwable.printStackTrace()
                    }
                } else {
                    LogUtils.e(TAG, "registerVHALSignal: failed with CarService not ready")
                }
            }
        }
    }

    private fun unregisterVHALSignal() {
        mCarPropertyManager?.unregisterCallback(this)
    }

    override fun onChangeEvent(carPropertyValue: CarPropertyValue<*>?) {
        if (PROP_HVAC_FUNC_IONS_SWITCH == carPropertyValue?.propertyId) {
            if (carPropertyValue?.status == CarPropertyValue.STATUS_AVAILABLE) {
                showIcon(carPropertyValue.value == true)
            } else {
                LogUtils.e(TAG, "onChangeEvent() with: propertyId = $PROP_HVAC_FUNC_IONS_SWITCH, not available!")
            }
        }
    }

    override fun onErrorEvent(propertyId: Int, areaId: Int) {
        LogUtils.e(TAG, "onErrorEvent() called with: propertyId = $propertyId, areaId = $areaId")
        showIcon(false)
    }

    private fun showIcon(show: Boolean){
        LogUtils.d(TAG, "showIcon() called with: show = $show")
        CoroutineScope(Dispatchers.Main).launch {
            visibility = if(show){
                View.VISIBLE
            } else {
                View.GONE
            }
        }
    }
}